//
//  UIScrollDocument.m
//  FMS
//
//  Created by Steven on 10/15/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "UIScrollDocument.h"
#import "AsynImageButton.h"

#define NUMBER_DOCUMENT_PER_PAGE 15

@implementation UIScrollDocument
@synthesize parent;
@synthesize scrollView;
@synthesize pageControl;
@synthesize itemArray;
@synthesize isDisplayButtonDelete;

- (id)initWithFrame:(CGRect)frame parent:(id)sender
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        parent = sender;
        self.backgroundColor = [UIColor clearColor];
        
        numberPage = 0;
    
        pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0,self.frame.size.height - 20,150,10)];
        pageControl.center = CGPointMake(self.frame.size.width/2,pageControl.center.y);
        pageControl.backgroundColor = [UIColor clearColor];
        [self addSubview:pageControl];
        [pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
        scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height-10)];
        [self addSubview:scrollView];
        
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissButtonDelete)];
        recognizer.numberOfTapsRequired = 1;
        [self addGestureRecognizer:recognizer];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

#pragma mark -
#pragma mark UIScrollViewDelegate stuff
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
    if (pageControlIsChangingPage) {
        return;
    }
    CGFloat pageWidth = _scrollView.frame.size.width;
    int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView
{
    pageControlIsChangingPage = NO;
}
- (void)setupPage
{
    if ([itemArray count] == 1)
        isDisplayButtonDelete = NO;
    if([itemArray count] % NUMBER_DOCUMENT_PER_PAGE == 0)
        numberPage = [itemArray count] / NUMBER_DOCUMENT_PER_PAGE;
    else
        numberPage = ([itemArray count] / NUMBER_DOCUMENT_PER_PAGE) + 1;
    for (id object in self.scrollView.subviews) {
        [object removeFromSuperview];
    }
	scrollView.delegate = self;
    [scrollView setCanCancelContentTouches:NO];
	
	scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
	scrollView.clipsToBounds = YES;
	scrollView.scrollEnabled = YES;
	scrollView.pagingEnabled = YES;
    CGFloat cx = 20;
    //    CGFloat cy = 30;
    for (int i=0; i<numberPage; i++) {
        for (int j =0; j < NUMBER_DOCUMENT_PER_PAGE; j++) {
            if(i*NUMBER_DOCUMENT_PER_PAGE+j >= [itemArray count])
                break;
            
            NSMutableDictionary *dict = [itemArray objectAtIndex:i*NUMBER_DOCUMENT_PER_PAGE+j];
            int row = j/5;
            int column = j%5;
            
            AsynImageButton *btn = [[AsynImageButton alloc] init];
            btn.frame = CGRectMake(cx + column*183,row*202+20, 115, 115);
            
            NSString *imageUrl = [dict objectForKey:@"imageUrl"];
            
            if (imageUrl == nil){
                [btn loadIMageFromImage:[UIImage imageNamed:@"btnAddDocument.png"]];
                btn.tag = 0;
            }
            else {
//                ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
//                [assetsLibrary assetForURL:[NSURL URLWithString:[dict objectForKey:@"imageUrl"]] resultBlock: ^(ALAsset *asset){
//                    ALAssetRepresentation *representation = [asset defaultRepresentation];
//                    CGImageRef imageRef = [representation fullResolutionImage];
//                    if (imageRef) {
//                        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
//                        imageView.image = [UIImage imageWithCGImage:imageRef scale:representation.scale orientation:representation.orientation];
//                        [btn loadIMageFromImage:imageView.image];
//            
//                    }
//                } failureBlock: ^(NSError *myerror){
//                    // Handle failure.
//                }];
                CBLDocument *document = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[dict objectForKey:@"_id"]];
                NSData *imageData = nil;
                if (document.currentRevision) {
                    CBLAttachment *attach = [document.currentRevision attachmentNamed:[dict objectForKey:@"fileName"]];
                    imageData = [attach body];
                    [btn loadIMageFromImage:[UIImage imageWithData:imageData]];
                }
                
                if ([btn backgroundImageForState:UIControlStateNormal] == nil) {
                    UIImage *image = [UIImage imageNamed:@"documentAttach.png"];
                    [btn loadIMageFromImage:image];
                }
                
                NSString *dateUpload = [NSDate stringFormatDateDisplayFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"dateUploaded"]]];
                [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                [btn setTitle:dateUpload forState:UIControlStateNormal];
                [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -140, 0)];
                
                btn.tag = i*NUMBER_DOCUMENT_PER_PAGE+j + 50;
                
                UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(displayButtonDelete:)];
                recognizer.delegate = self;
                [btn addGestureRecognizer:recognizer];
            }
            
            btn.dataDict = dict;
            
            //add event handling to button
            [btn addTarget:parent action:@selector(didSelectPhoto:) forControlEvents:UIControlEventTouchUpInside];
            
            [scrollView addSubview:btn];
        }
        cx += scrollView.frame.size.width;
    }
	self.pageControl.numberOfPages = numberPage;
    [self.pageControl setNeedsDisplay];
	[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
    
    if (isDisplayButtonDelete) {
        [self displayButtonDelete:nil];
    }
}

- (void) displayButtonDelete:(UILongPressGestureRecognizer*)recognizer {
    isDisplayButtonDelete = YES;
    for (int i=0; i<numberPage; i++) {
        for (int j =0; j < NUMBER_DOCUMENT_PER_PAGE; j++) {
            if(i*NUMBER_DOCUMENT_PER_PAGE+j >= [itemArray count])
                break;
            
            NSMutableDictionary *dict = [itemArray objectAtIndex:i*NUMBER_DOCUMENT_PER_PAGE+j];
            NSString *imageUrl = [dict objectForKey:@"imageUrl"];
            
            if (imageUrl == Nil);
            else {
                AsynImageButton *btnDocument = (AsynImageButton*)[scrollView viewWithTag: i*NUMBER_DOCUMENT_PER_PAGE+j + 50];
                AsynImageButton *btnDelete = [AsynImageButton buttonWithType:UIButtonTypeCustom];
                [btnDelete loadIMageFromImage:[UIImage imageNamed:@"btn-delete@2x.png"]];
                btnDelete.frame = CGRectMake(btnDocument.frame.origin.x-15, btnDocument.frame.origin.y-15, 30, 30);
                btnDelete.dataDict = btnDocument.dataDict;
                [btnDelete addTarget:parent action:@selector(deleteItemDocument:) forControlEvents:UIControlEventTouchUpInside];
                btnDelete.tag = 100000    ;
//                [btnDocument addSubview:btnDelete];
                [scrollView addSubview:btnDelete];
                
                //
                CABasicAnimation* rotationAnimation;
                rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
                rotationAnimation.fromValue = [NSNumber numberWithFloat: -M_PI * 0.01 ];
                rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 0.01 ];
                rotationAnimation.duration = 0.2;
                rotationAnimation.cumulative = NO;
                rotationAnimation.repeatCount = 100000;
                rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                
                [btnDocument.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
            }
        }
    }
}

- (void) dismissButtonDelete {
    if (isDisplayButtonDelete) {
        for (int i=0; i<numberPage; i++) {
            for (int j =0; j < NUMBER_DOCUMENT_PER_PAGE; j++) {
                if(i*NUMBER_DOCUMENT_PER_PAGE+j >= [itemArray count])
                    break;
                
                NSMutableDictionary *dict = [itemArray objectAtIndex:i*NUMBER_DOCUMENT_PER_PAGE+j];
                NSString *imageUrl = [dict objectForKey:@"imageUrl"];
                
                if (imageUrl == Nil);
                else {
                    AsynImageButton *btnDocument = (AsynImageButton*)[scrollView viewWithTag: i*NUMBER_DOCUMENT_PER_PAGE+j + 50];
//                    for (UIView *view in btnDocument.subviews) {
//                        if (view.tag == 1000) {
//                            [view removeFromSuperview];
//                        }
//                    }
                    for (UIView *view in scrollView.subviews) {
                        if (view.tag == 100000) {
                            [view removeFromSuperview];
                        }
                    }

                    
                    [btnDocument.layer removeAllAnimations];
                }
            }
        }
        isDisplayButtonDelete = NO;
    }
}

@end
